package web;

import Utils.web.servlet.BaseServlet;
import pojo.Task;
import pojo.User;
import service.Impl.TaskServiceImpl;
import service.TaskService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.time.LocalDateTime;

@WebServlet(name = "TaskServlet", value = "/TaskServlet")
public class TaskServlet extends BaseServlet {
    private TaskService taskService = new TaskServiceImpl();

    protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String taskname = request.getParameter("taskname");
        int status = "未完成".equals(request.getParameter("status")) ? 0 : 1;
        int id = Integer.parseInt(request.getParameter("id"));
        Task task = taskService.queryTaskById(id);
        task.setTaskname(taskname);
        task.setStatus(status);
        task.setTimeUpdate(LocalDateTime.now());
        taskService.updateTaskById(task);
        String pn = request.getParameter("pn");
        response.sendRedirect(request.getContextPath() + "/ClientServlet?action=pageByUserId&pn=" + pn);
    }

    protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String taskname = request.getParameter("taskname");
        User user= (User) request.getSession().getAttribute("user");
        int status = "未完成".equals(request.getParameter("status")) ? 0 : 1;
        Task task = new Task(null, taskname, status, LocalDateTime.now(), LocalDateTime.now(), user.getId());
        taskService.addTask(task);
        response.sendRedirect(request.getContextPath() + "/ClientServlet?action=pageByUserId");
    }

    protected void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        taskService.deleteTaskById(id);
        response.sendRedirect(request.getHeader("Referer"));
    }

    protected void queryTask(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        int id = Integer.parseInt(request.getParameter("id"));
        Task task = taskService.queryTaskById(id);
        request.setAttribute("task", task);
        request.setAttribute("action", "update");
        request.getRequestDispatcher("/pages/client/edit_task.jsp").forward(request, response);
    }

    protected void addRedirect(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("action", "add");
        request.getRequestDispatcher("/pages/client/edit_task.jsp").forward(request, response);
    }
}
